import { GenderType, Definition } from '../common/definition';
import { StoreEmployeeRelation } from '../store/storeEmployee.js';
import { Role } from '../enterpriseMgt/role.js';
import { Engine } from '../engine.js';
import { DateUtil } from '../../utils/dateUtil.js';
export function jsonToGender(val) {
    if (typeof val === 'number' && val >= 0 && val < Object.keys(GenderType).length) {
        return val;
    }
    return GenderType.unkown;
}

/// 员工管理
export const EmployeeMgrPageMode = {
    /// 正常模式，查阅模式或是编辑人员模式
    normal: 0,

    /// 单个人员选择模式
    singleSlection: 1,

    /// 多人员选择模式
    multiSelection: 2
}



export class Employee {
    constructor({
        id = '',
        name = '',
        role = [],
        stores = [],
        jobNumber = '',
        gender = GenderType.unkown,
        mobNumber = '',
        joinDate = null,
        title = '',
        email = '',
        loginAuthorized = false,
        userName = '',
        resetPwd = Definition.employeeDefaultInitPwd,
        available = true,
        remark = '',
        shortcut = '',
        pcShortcut = '',
        accessAllStoreData = false,
        accessAllWarehouseData = false
    }) {
        this.id = id;
        this.name = name;
        this.jobNumber = jobNumber;
        this.gender = gender;
        this.mobNumber = mobNumber;
        this.joinDate = joinDate || new Date();
        this.title = title;
        this.email = email;
        this.loginAuthorized = loginAuthorized;
        this.userName = userName;
        this.resetPwd = resetPwd;
        this.available = available;
        this.remark = remark;
        this.shortcut = shortcut;
        this.pcShortcut = pcShortcut;
        this.role = role;
        this.accessAllStoreData = accessAllStoreData;
        this.accessAllWarehouseData = accessAllWarehouseData;
        this._storeRelationList = stores;

        if (this._storeRelationList.length === 0) {
            this._storeRelationList.push(new StoreEmployeeRelation({
                id: '',
                store: Engine.profile?.getValideStore,  // 注意 profile ? 因为模拟数据时， profile 可能为空
                employee: this
            }));
        }
    }

    static empty() {
        return new Employee({});
    }

    static clone(employee) {
        const clonedRoles = employee.role.map(r => Role.clone(r));
        const clonedStores = [...employee._storeRelationList];
        return new Employee({
            ...employee,
            role: clonedRoles,
            stores: clonedStores
        });
    }

    static fromJson(json) {
        const roles = (json.roles || []).map(r => Role.fromJson(r));
        const stores = (json.stores || []).map(s => StoreEmployeeRelation.fromJson(s));

        return new Employee({
            id: json.accountId || '',
            name: json.nickName || '',
            jobNumber: json.jobNumber || '',
            gender: jsonToGender(json.usex),
            mobNumber: json.phoneNum || '',
            joinDate: json.workTime ? new Date(json.workTime) : null,
            title: json.workLevel || '',
            email: json.email || '',
            loginAuthorized: json.whetherCanLogin === 1,
            userName: json.loginName || '',
            available: json.status === 1,
            remark: json.remark || '',
            shortcut: json.shortcut || '',
            pcShortcut: json.pcShortcut || '',
            resetPwd: Definition.employeeDefaultInitPwd,
            accessAllStoreData: json.accessMerchantAllData === 1,
            accessAllWarehouseData: json.accessMerchantAllWarehouse === 1,
            role: roles,
            stores: stores
        });
    }


    // 复制json数据 与 fromJson 一一对应
    toCopyJson() {
        const ret = {
            accountId: this.id,
            nickName: this.name,
            jobNumber: this.jobNumber,
            usex: this.gender === GenderType.unkown ? null : this.gender,  // Changed from gender.index to match fromJson
            phoneNum: this.mobNumber,  // Changed from mobNumber to phoneNum
            workTime: this.joinDate,  // Changed from joinDate to workTime
            workLevel: this.title,  // Changed from title to workLevel
            email: this.email,
            whetherCanLogin: this.loginAuthorized ? 1 : 0,  // Changed from loginAuthorized to whetherCanLogin
            loginName: this.userName,  // Changed from userName to loginName
            status: this.available ? 1 : 0,  // Changed from available to status
            remark: this.remark,
            shortcut: this.shortcut,
            pcShortcut: this.pcShortcut,
            // loginPwd: this.resetPwd,  // 不要resetPwd
            accessMerchantAllData: this.accessAllStoreData ? 1 : 0,
            accessMerchantAllWarehouse: this.accessAllWarehouseData ? 1 : 0,
            roles: this.role.map(r => r.toCopyJson()),
            stores: this.storeRelationList.map(s => s.toCopyJson())
        };

        return ret;
    }
    toCopyJson2() {
        const roleIds = this.role.map(r => r.id).join(',');
        const ret = {
            accountId: this.id,
            nickName: this.name,
            jobNumber: this.jobNumber,
            gender: this.gender.index,  // todo 该转化可能会有错误
            mobNumber: this.mobNumber,
            joinDate: this.joinDate,
            title: this.title,
            email: this.email,
            loginAuthorized: this.loginAuthorized,
            userName: this.userName,
            resetPwd: this.resetPwd,
            available: this.available,
            remark: this.remark,
            shortcut: this.shortcut,
            pcShortcut: this.pcShortcut,
            roleIds: roleIds,
            stores: this.storeRelationList.map(s => s.toCopyJson())
        };

        return ret;
    }



    toJson() {
        const roleIds = this.role.map(r => r.id).join(',');

        const ret = {
            accountId: this.id,
            nickName: this.name,
            jobNumber: this.jobNumber,
            usex: this.gender === GenderType.unkown ? null : this.gender,
            phoneNum: this.mobNumber,
            workTime: this.joinDate ? DateUtil.getFullDateTime(this.joinDate) : null,
            workLevel: this.title,
            email: this.email,
            whetherCanLogin: this.loginAuthorized ? 1 : 0,
            loginName: this.userName,
            status: this.available ? 1 : 0,
            remark: this.remark,
            accessMerchantAllData: this.accessAllStoreData ? 1 : 0,
            accessMerchantAllWarehouse: this.accessAllWarehouseData ? 1 : 0,
            roleIds: roleIds,
            stores: this._storeRelationList.map(s => s.toJson())
        };

        if (this.resetPwd) {
            ret.loginPwd = this.resetPwd;
        }

        return ret;
    }

    get storeRelationList() {
        return [...this._storeRelationList];
    }

    removeStoreRelation(batch) {
        const index = this._storeRelationList.indexOf(batch);
        if (index !== -1) {
            this._storeRelationList.splice(index, 1);
            return true;
        }
        return false;
    }

    get storeList() {
        return this._storeRelationList.map(r => r.store);
    }

    setStore(stores) {
        // 删除不在传入列表中的门店
        for (let i = 0; i < this._storeRelationList.length; i++) {
            const rel = this._storeRelationList[i];
            if (!stores.some(s => s.id === rel.employee.id)) {
                this._storeRelationList.splice(i, 1);
                i--;
            }
        }

        // 添加新增的门店
        for (const store of stores) {
            if (!this._storeRelationList.some(r => r.employee.id === store.id)) {
                this._storeRelationList.push(new StoreEmployeeRelation({
                    id: '',
                    store,
                    employee: this
                }));
            }
        }
    }

    removeStores(idList) {
        for (const id of idList) {
            this._storeRelationList = this._storeRelationList.filter(rel => rel.store.id !== id);
        }
    }
}
